<template>
  <div class="app-container">
    <el-form ref="placeCodeForm" v-loading="formLoading" :rules="rules" :model="form" label-position="top">
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="标题" prop="title" style="width: 400px">
            <el-input v-model="form.title" placeholder="请输入标题" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="客户端" prop="userType" style="width: 400px">
            <el-cascader
              v-model="form.userType"
              placeholder="请选择文章分类"
              :options="userTypeOption"
              :props="{value:'id',label:'data'}"
              filterable></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="链接" prop="linkUrl" style="width: 400px">
            <el-input v-model="form.linkUrl" placeholder="请输入链接" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="广告位置" prop="seat" style="width: 400px">
            <el-cascader
              v-model="form.seat"
              placeholder="请选择广告位置"
              :options="seatOption"
              :props="{value:'id',label:'data'}"
              filterable></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <div class="input-info">
          <el-button type="primary" size="small" @click="addInput">添 加</el-button>
          <div v-for="(item,i) of eventPlanForm.matchKeywordArray" :key="i" >
            <el-row type="flex" :gutter="20">
              <el-col :span="24">
                <el-form-item label="图片" prop="imgUrl" style="width: 800px">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="form.imgUrlList[i]" :src="form.imgUrlList[i]" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="form.imgUrlList[i]" alt="">
              </el-dialog>
            </el-row>
            <span class="iconfont el-icon-remove text-red" style="cursor:pointer" @click="removeInput(i)">移除</span>
          </div>
          <div>
          </div>
        </div>
      </div>

    </el-form>
  </div>
</template>

<script>
import {getNewsByIdApi, getNewsTypeNameApi, insertAndUpdateNewsApi} from '@/api/placeCode'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {editAdvertisementApi, getAdvertisementByIdApi} from "@/api/advertisement";
export default {
  components: { Editor, Toolbar },
  name: 'PlaceCodeDetail',
  data(){
    return{
      editor: null,
      toolbarConfig: {
        excludeKeys: [
          // 排除菜单组，写菜单组 key 的值即可
          'group-video' // 去掉视频
        ]
      },
      editorConfig: { MENU_CONF: {}, placeholder: '' },
      mode: 'default',
      uploadUrl: process.env.VUE_APP_UPLOAD_API,
      dialogImageUrl: '',
      dialogVisible: false,
      form: {
        id: null,
        title:'',
        imgUrlList: [],
        userType:'',
        linkUrl: '',
        seat: 0,
      },
      rules: {
        title: [{ required: true, trigger: 'blur', message: '请输入标题' }],
        seat: [{ required: true, trigger: 'blur', message: '请选择广告位置' }],
        userType: [{ required: true, trigger: 'blur', message: '请选择客户端' }],
        imgUrlList: [{ required: true, trigger: 'blur', message: '请上传图片' }],
      },
      formLoading: false,
      userTypeOption: [
        {id:1,data: '个人'},
        {id:2,data: '企业'},
        {id:3,data: '全局'},
      ],
      seatOption: [
        {id:1,data: '小程序首页顶部轮播'},
        {id:2,data: 'PC招聘首页位置1'},
        {id:3,data: 'PC招聘首页位置2'},
        {id:4,data: '小程序首页弹出广告'},

      ],
      keywordList:[],
      ambiguityKeywordArray:'',
      eventPlanForm: {
        matchKeywordArray:[],
        ambiguityKeywordArray:[],
      },

    }
  },
  props:['id','closeDialog'],
  methods:{
    // 添加input
    addInput() {
      this.keywordList.push('')
      this.eventPlanForm.matchKeywordArray.push([])
    },
    // 移除input
    removeInput(key) {
      this.form.imgUrlList.splice(key, 1)
      this.eventPlanForm.matchKeywordArray.splice(key, 1)
    },


    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    handleAvatarSuccess(res, file) {
      this.form.imgUrlList.push(res.data);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    submit(){
      this.$refs.placeCodeForm.validate(valid => {
        if (valid) {
          const loading=this.$loading({
            text:'提交中'
          })
          if(this.form.id==null)
          {
            this.form.id = 0;
          }
          const form=JSON.parse(JSON.stringify(this.form));
          if(typeof this.form.userType!=='number'){
            form.userType=this.form.userType[0];
          }
          if(typeof this.form.seat!=='number'){
            form.seat=this.form.seat[0];
          }
          editAdvertisementApi(form).then((res)=>{
            this.$message.success('保存成功');
            this.closeDialog(0);
          }).catch(()=>{
            this.$message.error('保存失败');
          }).finally(()=>{
            loading.close();
          })
        } else {
          return false
        }
      })
    },
    getDetail(){
      this.formLoading=true;
      getAdvertisementByIdApi({id:this.id}).then((res)=>{
        this.form=res;
      }).finally(()=>{
        this.formLoading=false;
      })
    },
  },
  mounted() {
    if(this.id){
      this.getDetail();
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  created() {
    this.editorConfig.placeholder = '请输入使用说明内容...'
    this.editorConfig.MENU_CONF['uploadImage'] = {
      timeout: 5 * 1000, // 5s
      fieldName: 'image',
      // 用户自定义上传图片
      customUpload(file, insertFn) {
        var axios = require('axios')
        var FormData = require('form-data')
        var data = new FormData()
        data.append('file', file) // file 即选中的文件
        var config = {
          method: 'post',
          url: process.env.VUE_APP_UPLOAD_API, // 上传图片地址
          data: data
        }
        axios(config)
          .then(function(res) {
            const url = res.data.imgURL // 拼接成可浏览的图片地址
            insertFn(url, '使用说明', url) // 插入图片
          })
          .catch((res) => {
            console.log(res)
          })
      }
    }
  },
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
.w-e-bar.w-e-bar-show.w-e-toolbar{
  border: 1px solid;
}
.w-e-scroll{
  border: 1px solid;
}
</style>
<style scoped>
/*
*让select撑开
*/
.el-select,.el-cascader{
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
